<?php
namespace addons\yexam\service;

use app\admin\model\yexam\Answer;
use app\admin\model\yexam\ExamConfig;
use app\admin\model\yexam\ExamUser;
use app\admin\model\yexam\ExamUserLog;
use app\admin\model\yexam\QuestionLog;
use think\Exception;

class Exam
{

    public $model;
    public $error;

    public function __construct()
    {
        $this->model = new \app\admin\model\yexam\Exam();
    }

    /**
     * 获取考试列表
     * @param $page
     * @param $limit
     * @throws \think\Exception
     */
    public function getExamList($where,$page,$limit){
        $count = $this->model->where($where)->count();
        if($page){
            $data = $this->model->where($where)->page($page,$limit)->order("sort asc")->select();
        }else{
            $data = $this->model->where($where)->order("sort asc")->select();
        }



        return ['total'=>$count,'data'=>$data];
    }




    /**
     * 获取考试记录（已交卷）
     * @param $user_id
     * @param $page
     * @param $limit
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getRecordList($subject_id,$user_id,$page,$limit){
        $examUserModel = new ExamUser();

        $total = $examUserModel
            ->alias("exam_user")
            ->where(['user_id'=>$user_id,'subject_id'=>$subject_id,'up_status'=>2])->count();

        if($page){
            $data = $examUserModel
                ->alias("exam_user")
                ->where(['user_id'=>$user_id,'subject_id'=>$subject_id,'up_status'=>2])
                ->page($page,$limit)
                ->order("id desc")
                ->select();
        }else{
            $data = $examUserModel
                ->alias("exam_user")
                ->where(['user_id'=>$user_id,'subject_id'=>$subject_id,'up_status'=>2])
                ->order("id desc")
                ->select();
        }

        return ['total'=>$total,'data'=>$data];

    }

    /**
     * 判断系统时间，自动交卷
     * @param $exam_id
     */
    private function over_time_up($exam_id,$user_id){
        $examUserModel = new ExamUser();
        $examUser = $examUserModel->where(['exam_id'=>$exam_id,'user_id'=>$user_id,'up_status'=>1,'endtime'=>['elt',time()]])->find();
        if($examUser){
            $examUserLog = new ExamUserLog();
            $score = $examUserLog->where(['exam_user_id'=>$examUser['id']])->sum('score');
            $score = empty($score)?0:$score;
            $examUser->save(['up_status'=>2,'up_time'=>time(),'score'=>$score]);
        }
    }

    /**
     * 开始考试
     */
    public function begin($exam_id,$user_id){
        $examInfo = $this->model->where(['id'=>$exam_id])->find();
        if(empty($examInfo)){
            $this->error = "当前考试不存在或者不在考试时间范围内";
            return false;
        }
        if(empty($examInfo['question_ids'])){
            $this->error = "当前考试题目数量为0，请联系老师";
            return false;
        }
        //判断时间，自动交卷
        $this->over_time_up($exam_id,$user_id);

        //获取是否存在正在考试的记录
        $examUserModel = new ExamUser();
        $examUser = $examUserModel->where(['exam_id'=>$exam_id,'user_id'=>$user_id,'up_status'=>1])->find();
        if(empty($examUser)){
            if($examInfo['type'] == 1){
                $examUserModel = new ExamUser();
                $count = $examUserModel->where(['exam_id'=>$exam_id,'user_id'=>$user_id])->count();
                if($count){
                    $this->error = "当前考试只能参加一次";
                    return false;
                }
            }

            $endtime = time()+$examInfo['givetime']*60;
            $examUserModel = new ExamUser();
            $examUserModel->save([
                'subject_id'=>$examInfo['subject_id'],
                'type'=>$examInfo['type'],
                'exam_id'=>$examInfo['id'],
                'user_id'=>$user_id,
                'exam_name'=>$examInfo['exam_name'],
                'begintime'=>time(),
                'endtime'=>$endtime,
                'total_scode'=>$examInfo['score'],
                'question_ids'=>$examInfo['question_ids']]);

        }else{
            $endtime = $examUser['endtime'];
        }

        return $endtime;
    }

    /**
     * 考试答题卡
     */
    public function getCard($exam_id,$user_id){
        $examInfo = $this->model->where(['id'=>$exam_id,'start_date'=>['elt',date("Y-m-d H:i:s",time())],'end_date'=>['egt',date("Y-m-d H:i:s",time())]])->find();
        if(empty($examInfo)){
            $this->error = "当前考试不存在或者不在考试时间范围内";
            return false;
        }

        //判断时间，自动交卷
        $this->over_time_up($exam_id,$user_id);

        //获取当前考试当前用户的正在考试的考试记录
        $examUserModel = new ExamUser();
        $examUserInfo = $examUserModel->where(['exam_id'=>$exam_id,'user_id'=>$user_id,'up_status'=>1])->find();
        if(empty($examUserInfo)){
            $this->error = "本次考试已结束";
            return false;
        }

        $questionModel = new \app\admin\model\yexam\Question();
        $data = $questionModel
            ->alias("question")
            ->field("question.id,question.type,(log.id IS NOT NULL) as state")
            ->join("yexam_exam_user_log log","question.id=log.question_id and log.exam_user_id=".$examUserInfo['id'],"left")
            ->where(['question.id'=>['in',$examInfo['question_ids']]])
            ->order("question.type asc,id asc")
            ->select();

        return $data;
    }

    private function getCurrentExam($exam_id,$user_id){
        //获取当前考试当前用户的正在考试的考试记录
        $examUserModel = new ExamUser();
        $examUser = $examUserModel->where(['exam_id'=>$exam_id,'user_id'=>$user_id,'up_status'=>1])->find();
        return $examUser;
    }

    /**
     * 获取上次答题定位num
     */
    public function getLastPosition($exam_id,$user_id){
        $examInfo = $this->model->where(['id'=>$exam_id,'start_date'=>['elt',date("Y-m-d H:i:s",time())],'end_date'=>['egt',date("Y-m-d H:i:s",time())]])->find();
        if(empty($examInfo)){
            $this->error = "当前考试不存在或者不在考试时间范围内";
            return false;
        }

        $examUser = $this->getCurrentExam($exam_id,$user_id);        //获取当前考试当前用户的正在考试的考试记录
        if(empty($examUser)){
            $this->error = "本次考试已结束";
            return false;
        }


        $examUserLog = new ExamUserLog();
        $userlog = $examUserLog
            ->alias("log")
            ->field("log.question_id")
            ->join("yexam_question question","log.question_id=question.id",'inner')
            ->where(['exam_id'=>$exam_id,'exam_user_id'=>$examUser['id']])->order('log.lasttime desc')->find();
        if(empty($userlog)){
            return 1;
        }else{
            $questionModel = new \app\admin\model\yexam\Question();
            $questionList = $questionModel->field("id")->where(['id'=>['in',$examInfo['question_ids']]])->order("type asc,id asc")->select();
            $num = 1;
            foreach($questionList as $k=>$v){
                if($userlog['question_id'] == $v['id']){
                    break;
                }
                $num++;
            }
            return $num;
        }
    }


    /**
     * 获取题目详情
     * @throws Exception
     */
    public function getQuestion($exam_id,$question_id,$user_id){

        $examUser = $this->getCurrentExam($exam_id,$user_id);        //获取当前考试当前用户的正在考试的考试记录
        if(empty($examUser)){
            $this->error = "本次考试已结束";
            return false;
        }


        $questionModel = new \app\admin\model\yexam\Question();
        $question = $questionModel->field("id,question_name,type,right_answer,area")->where(['id'=>$question_id])->find();
        if(empty($question)){
            $this->error = "当前题目不存在";
            return false;
        }else{
            //获取答案
            if($question['type'] == 3){
                $question['answers'] = array(
                    '0' => array(
                        'answer' => "对",
                        'answer_code' => "1",
                        'id' => 1,
                        'question_id' => $question['id']
                    ),
                    '1' => array(
                        'answer' => "错",
                        'answer_code' => "0",
                        'id' => 2,
                        'question_id' => $question['id']
                    ),

                );
            }else{
                $answerModel = new Answer();
                $question['answers'] = $answerModel->where(['question_id'=>$question['id']])->select();
            }

            $examUserLog = new ExamUserLog();
            $userLog = $examUserLog->where(['exam_user_id'=>$examUser['id'],'question_id'=>$question['id']])->find();
            if($userLog){
                $question['user_answer'] = $userLog['user_answer'];
            }else{
                $question['user_answer'] = "";
            }

        }

        return $question;
    }


    /**
     * 手动交卷
     */
    public function up($exam_id,$user_id){
        $examInfo = $this->model->where(['id'=>$exam_id])->find();
        if(empty($examInfo)){
            $this->error = "当前考试不存在";
            return false;
        }

        //获取当前考试当前用户的正在考试的考试记录
        $examUserModel = new ExamUser();
        $examUser = $examUserModel->where(['exam_id'=>$exam_id,'user_id'=>$user_id,'up_status'=>1])->find();
        if(empty($examUser)){
            $this->error = "本次考试已结束";
            return false;
        }

        $examUserLog = new ExamUserLog();
        $score = $examUserLog->where(['exam_user_id'=>$examUser['id']])->sum('score');
        $score = empty($score)?0:$score;
        $up_time = time()>$examUser['endtime']?$examUser['endtime']:time();
        $examUser->save(['up_status'=>2,'up_time'=>$up_time,'score'=>$score]);

        //获取答对题目数
        $examUserLog = new ExamUserLog();
        $right_num = $examUserLog->where(['exam_user_id'=>$examUser['id'],'state'=>1])->count();

        //总题数
        $questionModel = new \app\admin\model\yexam\Question();
        $num = $questionModel->where(['id'=>['in',$examInfo['question_ids']]])->count();

        return ['score'=>$score,'up_time'=>$up_time,'usetime'=>$up_time-$examUser['begintime'],'dadui_num'=>$right_num,'total_num'=>$num];

    }

    /**
     * 答题
     */
    public function answer($exam_id,$user_id,$question_id,$answer){
        //判断时间，自动交卷
        $this->over_time_up($exam_id,$user_id);

        //获取当前考试当前用户的正在考试的考试记录
        $examUserModel = new ExamUser();
        $examUser = $examUserModel->where(['exam_id'=>$exam_id,'user_id'=>$user_id,'up_status'=>1])->find();
        if(empty($examUser)){
            $this->error = "本次考试已结束";
            return false;
        }

        //获取当前题目正确/错误
        $questionModel = new \app\admin\model\yexam\Question();
        $questionInfo = $questionModel->where(['id'=>$question_id])->find();
        if(empty($questionInfo)){
            $this->error = "本次题目不存在";
            return false;
        }

        $examConfigModel = new ExamConfig();
        $config = $examConfigModel->where(['exam_id'=>$exam_id])->find();
        if(empty($config)){
            $_score = 0;
        }else{
            $_score = $config['score'];
        }


        if ($answer == $questionInfo['right_answer']) {
            $score = $_score;
            $state = 1;
        }else{
            $score = 0;
            $state = 0;
        }

        //获取题目分数
        $examUserLog = new ExamUserLog();
        if($userlog = $examUserLog->where(['exam_id'=>$exam_id,'exam_user_id'=>$examUser['id'],'question_id'=>$question_id])->find()){
            $userlog->save([
                'user_answer' => $_POST['answer'],
                'lasttime' => time(),
                'state' => $state,
                'score' => $score
            ]);
        }else{
            $examUserLog = new ExamUserLog();
            $examUserLog->save([
                'exam_user_id' => $examUser['id'],
                'user_id' => $user_id,
                'exam_id' => $exam_id,
                'question_id' => $question_id,
                'user_answer' => $answer,
                'lasttime' => time(),
                'state' => $state,
                'score' => $score
            ]);
        }

        return true;
    }


    /**
     * 获取考试错题列表
     */
    public function getErrorLogList($subject_id,$type,$user_id,$page,$limit){

        $logModel = new ExamUserLog();
        $count = $logModel
            ->alias("log")
            ->join("yexam_exam_user exam_user","log.exam_user_id=exam_user.id",'inner')
            ->join("yexam_exam exam","log.exam_id=exam.id",'inner')
            ->where(['exam.subject_id'=>$subject_id,'exam.type'=>$type,'log.user_id'=>$user_id,'log.state'=>0])->group("exam.id")->count();
        if($page){
            $data = $logModel
                ->alias("log")
                ->field("exam_user.id,exam_user.exam_name,count(log.id) as error_num")
                ->join("yexam_exam_user exam_user","log.exam_user_id=exam_user.id",'inner')
                ->join("yexam_exam exam","log.exam_id=exam.id",'inner')
                ->where(['exam.subject_id'=>$subject_id,'exam.type'=>$type,'log.user_id'=>$user_id,'log.state'=>0])
                ->page($page,$limit)
                ->group("exam_user.id")
                ->select();
        }else{
            $data = $logModel
                ->alias("log")
                ->field("exam_user.id,exam_user.exam_name,count(log.id) as error_num")
                ->join("yexam_exam_user exam_user","log.exam_user_id=exam_user.id",'inner')
                ->join("yexam_exam exam","log.exam_id=exam.id",'inner')
                ->where(['exam.subject_id'=>$subject_id,'exam.type'=>$type,'log.user_id'=>$user_id,'log.state'=>0])
                ->group("exam_user.id")
                ->select();
        }

        return ['total'=>$count,'data'=>$data];
    }


    /**
     * 考试错题答题卡
     */
    public function getErrorCard($exam_user_id,$user_id){

        //获取当前考试当前用户的正在考试的考试记录
        $examUserModel = new ExamUser();
        $examUserInfo = $examUserModel->where(['id'=>$exam_user_id,'user_id'=>$user_id])->find();
        if(empty($examUserInfo)){
            $this->error = "本次考试已结束";
            return false;
        }

        $questionModel = new \app\admin\model\yexam\Question();
        $data = $questionModel
            ->alias("question")
            ->field("question.id,log.state")
            ->join("yexam_exam_user_log log","question.id=log.question_id and log.exam_user_id=".$examUserInfo['id'],"inner")
            ->where(['question.id'=>['in',$examUserInfo['question_ids']],'log.state'=>0])
            ->order("question.type asc,id asc")
            ->select();

        return $data;
    }



}